package com.heima.wemedia.gateway.filter;


import com.heima.wemedia.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class AuthorizeFilter implements Ordered, GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        if (request.getURI().getPath().contains("/login"))
            return chain.filter(exchange);


        log.info("请求路径:{}", request.getURI());
        log.info( "请求头:{}", request.getHeaders());
//        log.info("请求token:{}", request.getHeaders().containsKey("token"));
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank( token)) {
            log.error("token为空");
//            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            if (AppJwtUtil.verifyToken(claims) == 1 || AppJwtUtil.verifyToken(claims) == 2) {
                log.error("token过期");
                //            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");

                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            Integer userId = (Integer) claims.get("id");
            ServerHttpRequest httpRequest = request.mutate().header("userId", userId.toString()).build();
            exchange.mutate().request(httpRequest).build();

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


        return chain.filter(exchange);
    }

    /**
     * 优先级设置  值越小  优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
